/**
 * base64
 * @param val
 */
import Base64 from "./lib/base64-lib";

// let replaceObj = {
// 	"+": "!",
// 	"/": "-",
// }

export default {
	/**
	 * 加密
	 * @param {object|string} val
	 * @param {boolean} isUrl 是否将转换的字符作为URL(这样会将“+”改成“!”,将“/”改成“-”)
	 * @returns {string|null}
	 */
	encode(val, isUrl) {
		if (typeof val == "object") {
			val = JSON.stringify(val);
		} else {
			val = val || (val + "");
		}
		let _value = Base64.encode(val) || null;
		if (isUrl && _value) {
			/**将所有的‘+’替换成‘!’，将所有的‘/’替换成‘-’*/
            _value = _value.replace(/\+/g, "!");
           _value = _value.replace(/\//g, "-");

			/*let regStr = '(' + Object.keys(replaceObj).map(it => '\\' + it).join('|') + ')'
			let reg = new RegExp(regStr, 'g')
			_value = _value.replace(reg, it => replaceObj[it]);*/
		}
		return _value;
	},

	/**
	 * 解密
	 * @param {string} val base64的字符编码
	 * @param {boolean} isUrl 是否是作为了url的字符(这样会将“!”改成“+”,将“-”改成“/”)
	 * @returns {object|string}
	 */
	decode: function (val) {
		val += "";
         /**将所有的‘!’替换成‘+’，将所有的‘-’替换成‘/’*/
		val = val.replace(/!/g, "\+");
		val = val.replace(/-/g, "\/");

       /*let regStr = '(' + Object.values(replaceObj).map(it => '\\' + it).join('|') + ')'
       let reg = new RegExp(regStr, 'g')
       val = val.replace(reg, it => {
          for(let key in replaceObj){
             if(replaceObj[key] === it){
                return key;
             }
          }
          return it;
       });*/

		let _value = Base64.decode(val) || "";
		try {
			_value = JSON.parse(_value);
			return _value;
		} catch (e) {
			return _value;
		}
	},
};